package com.cs.cssupplier.controller;

import com.cs.cssupplier.domain.*;
import com.cs.cssupplier.domain.vo.CsSupplierVO;
import com.cs.cssupplier.mapper.CsSupplierMapper;
import com.cs.cssupplier.mapper.CsWinningResultsMapper;
import com.cs.cssupplier.service.CsAccessService;
import com.cs.cssupplier.service.CsCodeRulesService;
import com.cs.cssupplier.service.CsOperatorService;
import com.cs.cssupplier.service.CsSupplierService;
import com.cs.cssupplier.utils.CodeRuleHelp;
import com.cs.cssupplier.utils.CodeRuleUtil;
import com.cs.cssupplier.utils.FileUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.SysFile;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author：lyj
 * @Package：com.cs.cssupplier.controller
 * @Project：RuoYi-Cloud-master
 * @name：CsSupplierController
 * @Date：2024/11/13 11:37
 * @Filename：CsSupplierController
 */
@RestController
@RequestMapping("/supplier")
public class CsSupplierController extends BaseController {
    @Resource
    private CsSupplierMapper csSupplierMapper;

    @Resource
    private CsCodeRulesService codeRulesService;

    @Resource
    private CsAccessService csAccessService;

    @Resource
    private CsOperatorService csOperatorService;
    @Resource
    private RemoteFileService remoteFileService;

    @Autowired
    private CsWinningResultsMapper mapper;

    private boolean flag=true;

    @GetMapping("/whole")
    public TableDataInfo wholeList(){
        startPage();
        List<CsSupplier> list=csSupplierMapper.selectCsSupplier();
        System.out.println(list);
        return getDataTable(list);
    }

    @GetMapping("/list")
    public TableDataInfo list(CsSupplier supplier){
        startPage();
        List<CsSupplier> list=csSupplierMapper.selectCsSupperList(supplier);
        return getDataTable(list);
    }
    @GetMapping("/noSupplierList")
    public TableDataInfo noSupplierList(CsSupplier supplier){
        startPage();
        List<CsSupplier> noSupplierList=csSupplierMapper.selectNoCsSupperList(supplier);
        return getDataTable(noSupplierList);
    }
    @GetMapping("/supplierBagList")
    public TableDataInfo supplierBagList(CsSupplier supplier){
        startPage();
        List<CsSupplier> supplierBagList=csSupplierMapper.selectCsSupperBadList(supplier);
        return getDataTable(supplierBagList);
    }

    /**
     * 获得供应商全部(下拉框)
     * @return
     */
    @GetMapping("/getSupplierList")
    public R<List<CsSupplier>> getSupplierList(){
        return R.ok(csSupplierMapper.getSupplierList());
    }

    /**
     * 获得供应商全部 分页版
     * @return
     */
    @GetMapping("/getSupplierListPage")
    public TableDataInfo getSupplierListPage(CsSupplier supplier){
        startPage();
        List<CsSupplierVO> supplierList = csSupplierMapper.getSupplierVOList();
        return getDataTable(supplierList);
    }

    /**
     * 添加供应商/添加业务经办人
     *
     * 有问题，等一下解决
     *
     * @param map
     * @return
     * @throws ParseException
     */
    @PostMapping
    public AjaxResult add(@RequestBody Map<String,Object> map) throws ParseException{
        Long userid = SecurityUtils.getLoginUser().getUserid();
        Long sipplierByUserId = mapper.getSipplierByUserId(userid);//这才是供应商id
        System.out.println(sipplierByUserId+"这才是供应商id");
        System.out.println("添加");
        // 生成年月日字符串
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(new Date());

        // 生成UUID
        UUID uuid = UUID.randomUUID();
        String uuidString = uuid.toString();

        // 取UUID的后六位作为六位随机数
        String randomStr = uuidString.substring(uuidString.length() - 6);

        //准入编号
        String result = "ZR" + dateStr + randomStr;
        CsAccess access=new CsAccess();
        access.setZr_id(access.getZr_id());
        access.setZr_bnumber(result);
        access.setZr_promoter(map.get("h_juridical").toString());
        System.out.println(access);
        int res=csAccessService.addAccess(access);
        if (res>0){
            CsSupplier supplier=new CsSupplier();
            System.out.println(access.getZr_id());
            supplier.setZr_id(access.getZr_id());
            supplier.setHid(sipplierByUserId);
            // 供应商名称
            if (map.get("h_name")!=null){
                supplier.setH_name(map.get("h_name").toString());
            }
            // 统一社会信用代码
            if (map.get("h_credit_code")!=null){
                supplier.setH_credit_code(map.get("h_credit_code").toString());
            }
            // 单位注册地
            if (map.get("h_incorporation")!=null){
                supplier.setH_incorporation(map.get("h_incorporation").toString());
            }
            // 机构类型
            if (map.get("h_institution")!=null){
                supplier.setH_institution(map.get("h_institution").toString());
            }
            // 企业性质
            if (map.get("h_quality")!=null){
                supplier.setH_quality(map.get("h_quality").toString());
            }
            // 成立日期
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            if (map.get("h_start_time")!=null){
                supplier.setH_start_time(format.parse(map.get("h_start_time").toString()));
            }
            // 法人/负责人
            if(map.get("h_juridical")!=null){
                supplier.setH_juridical(map.get("h_juridical").toString());
            }
            // 法人/负责人身份证号
            if (map.get("h_juridical_identity")!=null){
                supplier.setH_juridical_identity(map.get("h_juridical_identity").toString());
            }
            // 单位联系地址
            if (map.get("h_address")!=null){
                supplier.setH_address(map.get("h_address").toString());
            }
            // 登录供应商账号
            if (map.get("h_loginaccount")!=null){
                supplier.setH_loginaccount(map.get("h_loginaccount").toString());
            }
            // 登录供应商密码
            if (map.get("h_password")!=null){
                supplier.setH_password(map.get("h_password").toString());
            }
            // 单位注册地址
//            if (map.get("h_sign_address")!=null){
//                supplier.setH_sign_address(map.get("h_sign_address").toString());
//            }
            // 公司简历
            if (map.get("h_desc")!=null){
                supplier.setH_desc(map.get("h_desc").toString());
            }
            // 开户行
            if (map.get("h_bank")!=null){
                supplier.setH_bank(map.get("h_bank").toString());
            }
            // 银行账号
            if (map.get("h_account")!=null){
                supplier.setH_account(map.get("h_account").toString());
            }
            // 开户地址
            if (map.get("h_bank_address")!=null){
                supplier.setH_bank_address(map.get("h_bank_address").toString());
            }
            // 单位注册电话
            if (map.get("h_sign_phone")!=null){
                supplier.setH_sign_phone(map.get("h_sign_phone").toString());
            }
            // 营业执照扫描件
            if (map.get("h_copies")!=null){
                supplier.setH_copies(map.get("h_copies").toString());
            }
            // 法人/负责人身份证扫描件
            if (map.get("h_juridical_copies")!=null){
                supplier.setH_juridical_copies(map.get("h_juridical_copies").toString());
            }
            // 注册资本
            if (map.get("h_capital")!=null){
                supplier.setH_capital(Long.valueOf(map.get("h_capital").toString()));
            }
            // 实缴资本
            if (map.get("h_actual_capital")!=null){
                supplier.setH_actual_capital(Long.valueOf(map.get("h_actual_capital").toString()));
            }
            System.out.println(supplier);
            int ress=csSupplierMapper.updateSupplier(supplier);
            if (ress>0){
                //添加业务经办人
                CsOperator operator=new CsOperator();
                operator.setHid(sipplierByUserId);
                // 姓名
                if (map.get("yw_name")!=null){
                    operator.setYw_name(map.get("yw_name").toString());
                }
                // 身份证
                if (map.get("yw_idcrad")!=null){
                    operator.setYw_idcrad(map.get("yw_idcrad").toString());
                }
                // 电话
                if (map.get("yw_phone")!=null){
                    operator.setYw_phone(map.get("yw_phone").toString());
                }
                // 邮箱
                if (map.get("yw_mailbox")!=null){
                    operator.setYw_mailbox(map.get("yw_mailbox").toString());
                }
                // 身份证扫描件
                if (map.get("yw_scan_idcard")!=null){
                    operator.setYw_scan_idcard(map.get("yw_scan_idcard").toString());
                }
                if (flag){
                    csOperatorService.insertOperator(operator);
                    flag=false;
                    return AjaxResult.success("添加成功");
                }else {
                    return toAjax(csOperatorService.updateOperator(operator));
                }
            }
        }
        return AjaxResult.error("操作失败");
    }

    /**
     * 修改供应商信息
     * @param csSupplier
     * @return
     */
    @PutMapping
    public AjaxResult updateSupplier(@RequestBody CsSupplier csSupplier){
        return toAjax(csSupplierMapper.updateSupplier(csSupplier));
    }

    /**
     * 批量删除供应商信息
     * @param hids
     * @return
     */
    @DeleteMapping("/{hids}")
    public AjaxResult deleteSupplier(@PathVariable Long [] hids){
        return toAjax(csSupplierMapper.deleteListSupplier(hids));
    }
    /**
     * 根据id查询供应商列表
     * @param hid
     * @return
     */
    @GetMapping(value = "/{hid}")
    public AjaxResult queryHid(@PathVariable("hid") Long hid){
        Long userid = SecurityUtils.getLoginUser().getUserid();
        Long sipplierByUserId = mapper.getSipplierByUserId(userid);//这才是供应商id
        System.out.println(sipplierByUserId+"这才是供应商id");
        CsSupplier supplier=csSupplierMapper.selectSupplierHid(userid);
        String copy=supplier.getH_juridical_copies();
        if (copy!=null){
            String [] arr=copy.split(",");
            supplier.setIdCardCopies(arr);
            System.out.println(arr+"DSADSD");
        }
        return success(supplier);
    }
    @GetMapping(value = "/cd/{hid}")
    public AjaxResult queryAsHid(@PathVariable("hid") Long hid){
        return success(csSupplierMapper.selectSupplierHid(hid));
    }
    /**
     * 获取准入供应商详细信息
     */
    @GetMapping("/access/{zr_id}")
    public AjaxResult getInfoByZrId(@PathVariable("zr_id") Long zr_id) {
        CsSupplier csSupplier = csSupplierMapper.selectCsSupplierByZrId(zr_id);
        String copy = csSupplier.getH_juridical_copies();
        if (copy != null) {
            String[] arr = copy.split(",");
            csSupplier.setIdCardCopies(arr);
        }
        return success(csSupplier);
    }

    @GetMapping("/downloadZip")
    public void downloadZip(@RequestParam String url, HttpServletResponse response) {
        //下载压缩包
        FileUtil.downloadFiles(url, response);
    }
    @PostMapping("/upload1")
    public AjaxResult upload1(MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            R<SysFile> fileResult = remoteFileService.upload(file);
            System.out.println("fileResult:" + fileResult.getData().getName() + "\t" + fileResult.getData().getUrl());
            System.out.println("文件上传成功！。。。。");
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                return AjaxResult.error("文件服务异常，请联系管理员");
            }
            return AjaxResult.success(fileResult.getData());
        }
        return AjaxResult.error("上传文件异常，请联系管理员");
    }
}
